package com.bill99.golden.inf.sso.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bill99.golden.inf.sso.mdp.dto.DestroyTokenRequestDto;
import com.bill99.golden.inf.sso.util.CM;

public class DestroyRemoteSSOThread extends Thread {
	private static Log log = LogFactory.getLog(DestroyRemoteSSOThread.class);
	static Map<String, Queue<DestroyTokenRequestDto>> ssoMap = new HashMap<String, Queue<DestroyTokenRequestDto>>();
	static Object lock = new Object();
	static boolean isRun = false;
	static final long waitTime = 1000 * 90;
	static Map<String, Integer> runFlagMap = new HashMap<String, Integer>();
	String appCode;
	String logoutUrl;

	public DestroyRemoteSSOThread(String appCode, String logoutUrl) {
		this.appCode = appCode;
		this.logoutUrl = logoutUrl;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		synchronized (lock) {
			Integer n = runFlagMap.get(this.appCode);
			if (n == null)
				n = new Integer(0);
			n++;
			runFlagMap.put(this.appCode, n);
		}
		try {
			Thread.sleep(2000);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Queue<DestroyTokenRequestDto> queue = ssoMap.get(this.appCode);
		if (queue == null) {
			runFlagMap.remove(this.appCode);
			return;
		}
		log.debug("destroy remote session:::::queue size=" + queue.size());
		while (queue.isEmpty() == false) {
			try {
				DestroyTokenRequestDto r = queue.remove();
				if (r != null)
					this.destryRemoteSSOBuffer(r);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		log.debug("destroy remote session:::::end!!!!!!");
		synchronized (lock) {
			Integer n = runFlagMap.get(this.appCode);
			if (n == null)
				n = new Integer(0);
			else
				n--;
			runFlagMap.put(this.appCode, n);
		}
	}

	private void destryRemoteSSOBuffer(DestroyTokenRequestDto r) {
		HttpClient http = new HttpClient();
		// System.out.println("createToken:::" + r);
		try {
			HttpClientParams ps = http.getParams();
			ps.setContentCharset("UTF-8");
			ps.setHttpElementCharset("UTF-8");
			ps.setCredentialCharset("UTF-8");
			PostMethod pm = new PostMethod(this.logoutUrl);
			pm.addParameter(new NameValuePair("cmd", "logout"));
			pm.addParameter(new NameValuePair("appCode", CM.stringNoNull(r
					.getAppCode())));
			pm.addParameter(new NameValuePair("token", CM.stringNoNull(r
					.getToken())));
			pm.addParameter(new NameValuePair("userIp", CM.stringNoNull(r
					.getUserIp())));
			pm.addParameter(new NameValuePair("explorerType", CM.stringNoNull(r
					.getExplorerType())));

			int status = http.executeMethod(pm);
			if (status == HttpStatus.SC_OK) {
				log.debug("销毁远程SSO信息成功：logoutUrl=" + logoutUrl + " " + r);
			} else {
				log.error("销毁远程SSO信息失败：logoutUrl=" + logoutUrl + " " + r);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("销毁远程SSO信息失败：logoutUrl=" + logoutUrl + " " + r, e);
			e.printStackTrace();
		}
	}

	public static void destryRemoteSSOBuffer(String appCode,
			DestroyTokenRequestDto r, String logoutUrl) {
		Queue<DestroyTokenRequestDto> queue = ssoMap.get(appCode);
		if (queue == null) {
			queue = new LinkedBlockingQueue<DestroyTokenRequestDto>();
			ssoMap.put(appCode, queue);
		}
		queue.add(r);
		int runningCnt = 0;
		synchronized (lock) {
			Integer n = runFlagMap.get(appCode);
			if (n != null) {
				runningCnt = n.intValue();
			}
		}
		if (runningCnt <= 0) {
			Thread t = new DestroyRemoteSSOThread(appCode, logoutUrl);
			t.start();
		}
	}
}
